package com.zefor.task;

import com.zefor.pojo.EnvironmentPojo;
import com.zefor.utils.AdmqUtil;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.Save;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.epm.eb.common.model.BgDynamicObject;
import org.apache.cxf.Bus;
import org.hibernate.validator.internal.util.logging.Log_$logger;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*
 * 环境数据采集定时任务
 * */
public class AccessEnvTask extends AbstractTask {


    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        DynamicObject[] corrals = BusinessDataServiceHelper.load("n716_corral", "id,name,n716_farm_basedata", null);

        //获取环境记录,判断是否是今天
        DynamicObject[] envInfos = BusinessDataServiceHelper.load("n716_env_info", "id,n716_basedatafield,n716_basedatafield1,n716_avg_temperature,n716_avg_humidity,n716_avg_co2,n716_avg_lux,createtime", null, "createtime desc", corrals.length);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<EnvironmentPojo> list = AdmqUtil.getEnvironment();
        for (int i = 0; i < corrals.length; i++) {
            //mq中读取的信息
            EnvironmentPojo item = list.get(i);
            //栏舍信息
            DynamicObject corral = corrals[i];
            //是当天
            if (envInfos.length > 0 && format.format((Date) envInfos[0].get("createtime")).equals(format.format(System.currentTimeMillis()))) {
                //在原表单中添加数据
                DynamicObject single = BusinessDataServiceHelper.loadSingle(envInfos[i].getString("id"), "n716_env_info");
                DynamicObjectCollection entryentity = single.getDynamicObjectCollection("n716_entryentity");
                //重新设置平均数
                double sum1 = entryentity.stream().mapToDouble(p -> Double.parseDouble(p.getString("n716_decimalfield"))).sum();
                double sum2 = entryentity.stream().mapToDouble(p -> Double.parseDouble(p.getString("n716_decimalfield1"))).sum();
                double sum3 = entryentity.stream().mapToDouble(p -> Double.parseDouble(p.getString("n716_integerfield"))).sum();
                double sum4 = entryentity.stream().mapToDouble(p -> Double.parseDouble(p.getString("n716_integerfield1"))).sum();
                envInfos[i].set("n716_avg_temperature", (sum1 + item.getTemperature()) / (entryentity.size() + 1));
                envInfos[i].set("n716_avg_humidity", (sum2 + item.getHumidity()) / (entryentity.size() + 1));
                envInfos[i].set("n716_avg_co2", (long) ((sum3 + item.getCarbondioxide()) / (entryentity.size() + 1)));
                envInfos[i].set("n716_avg_lux", (long) ((sum4 + item.getIllumination()) / (entryentity.size() + 1)));
                DynamicObject temp = new DynamicObject(entryentity.getDynamicObjectType());
                temp.set("n716_datetimefield1", item.getTimestamp().getTime() / 1000);
                temp.set("n716_decimalfield", item.getTemperature());
                temp.set("n716_decimalfield1", item.getHumidity());
                temp.set("n716_integerfield", item.getCarbondioxide());
                temp.set("n716_integerfield1", item.getIllumination());
                entryentity.add(temp);
                SaveServiceHelper.save(new DynamicObject[]{single});
                SaveServiceHelper.save(new DynamicObject[]{envInfos[i]});
            } else {
                //不是当天
                DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("n716_env_info");
                dynamicObject.set("billstatus", "A");
                dynamicObject.set("n716_basedatafield", corral.getDynamicObject("n716_farm_basedata"));
                dynamicObject.set("n716_basedatafield1", corral);
                dynamicObject.set("n716_avg_temperature", +item.getTemperature());
                dynamicObject.set("n716_avg_humidity", item.getHumidity());
                dynamicObject.set("n716_avg_co2", item.getCarbondioxide());
                dynamicObject.set("n716_avg_lux", item.getIllumination());
                DynamicObjectCollection entryentity = dynamicObject.getDynamicObjectCollection("n716_entryentity");
                DynamicObject temp = new DynamicObject(entryentity.getDynamicObjectType());
                temp.set("n716_datetimefield1", item.getTimestamp().getTime() / 1000);
                temp.set("n716_decimalfield", item.getTemperature());
                temp.set("n716_decimalfield1", item.getHumidity());
                temp.set("n716_integerfield", item.getCarbondioxide());
                temp.set("n716_integerfield1", item.getIllumination());
                entryentity.add(temp);
                SaveServiceHelper.saveOperate("n716_env_info", new DynamicObject[]{dynamicObject}, OperateOption.create());
            }
        }
    }
}
